import config from 'config';

function getStorage(key) {
	return uni.getStorageSync(`$${config.clientId}_${key}`);
}

function setStorage(options, value) {
	if (typeof options === 'string')
		return uni.setStorageSync(`$${config.clientId}_${options}`, value);
	if (options.key) options.key = `$${config.clientId}_${options.key}`;
	uni.setStorage(options);
}

function removeStorage(options) {
	if (typeof options === 'string')
		return uni.removeStorageSync(`$${config.clientId}_${options}`);
	if (options.key) options.key = `$${config.clientId}_${options.key}`;
	uni.removeStorage(options);
}

function queryStringToObject(str) {
	var obj = {}
	var splitStringArray = str.substring(str.indexOf("?") + 1).split('&');
	splitStringArray.forEach(item => {
		if (item) {
			var kv = item.split('=');
			obj[kv[0]] = kv[1];
		}
	});
	return obj;
}

function objectToQueryString(obj) {
	var queryString = '?';
	for (let key in obj) {
		queryString += `${key}=${obj[key]}&`;
	}
	queryString = queryString.replace(/&$/, '');
	if (queryString === '?') {
		queryString = '';
	}
	return queryString;
}

function queryStringRemoveParams(url, names) {
	if (typeof(names) === 'string') {
		names = [names];
	}
	var obj = queryStringToObject(url);
	for (var i = 0; i < names.length; i++) {
		delete obj[names[i]];
	}
	return objectToQueryString(obj);
}

function toErrorPage(code, message) {
	uni.redirectTo({
		url: `/pages/error/error?code=${code}&message=${message}`
	});
}

function toLinkPage(link, title) {
	if (!link) return
	if (!title) title = config.appName
	if (link.startsWith('/')) {
		uni.navigateTo({
			url: link
		});
	} else {
		uni.navigateTo({
			url: `/pages/webview/webview?link=${link}&title=${title}`
		});
	}
}

function navigateBack() {
	var pages = getCurrentPages();
	if (pages.length > 1) {
		uni.navigateBack();
	} else {
		uni.reLaunch({
			url: '/'
		});
	}
}

export default {
	getStorage,
	setStorage,
	removeStorage,
	queryStringToObject,
	objectToQueryString,
	queryStringRemoveParams,
	toErrorPage,
	toLinkPage,
	navigateBack
}
